const express = require('express');
const router = express.Router();
const db = require("../../util/dbConfig/dbConfig")

//用户登录
router.post('/',async (req,res) => {
    let {phone,password} = req.body
    //参数错误
    if(!phone || !password){
        return res.send({
            code: 1,
            msg: '请输入完整的账号与密码'
        })
    }
    //登录
    try{
        let sql = 'select * from user where PHONENUM=?'
        let sqlArr = [phone]
        let callBack = (err,data) => {
            if(err){
                console.log(err,'查询错误');
            }else if(data.length === 0){
                //如果查询返回值data为空数组，则返回  无此用户
                return res.send({
                    code: 2,
                    msg: '无此用户'
                })
            }else if(data[0].PASSWORD !== password ){
                console.log(data[0].PASSWORD);
                //如果有此用户。但密码不匹配则返回  密码错误
                return res.send({
                    code: 2,
                    msg: '密码错误，请重试'
                })
            }else  {
                //登录成功，保存session
                let userInfo = {
                    user: data[0].NAME,
                    _id: data[0].ID,
                    admin: data[0].MANAGE
                }
                req.session.userInfo = userInfo
                console.log('登录成功，此时的响应体session',req.session);
                //则返回  登录成功
                return res.send({
                    code: 0,
                    msg: '登录成功'
                })
            }

        }
        db.sqlConnect(sql,sqlArr,callBack)

    }catch (e) {
        console.log('login路由登录错误',e);
        return res.send({
            code: 4,
            msg: '服务器错误，请稍后再试'
        })
    }
})


module.exports = router
